<?php

namespace Pm\Controllers;

use Admin\Models\pm\XhpmSchedule;
use Admin\Models\pm\XhpmProject;
use Admin\Models\pm\XhpmProjectTask;
use Admin\Models\pm\XhpmProjectCount;
use Helpers\Main;
use Helpers\Assets;
use Helpers\Template;
use Helpers\User;
use Admin\Models\hrm\XhhrmDepart;
use Modules\Power;

class ScheduleController extends ControllerBase
{

    private static $schedule_types = [
        1 => '自建',
        2 => '分配',
    ];

    /**
     * 首页展示
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180731
     */
    public function homeScheduleAction()
    {
        $this->view->pick('schedule/home');
        Assets::importJs('js/myMain.js');
        Assets::easyUI('js/schedule/home.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::FullCalendar();
        Main::showNavPosition();
    }

    /**
     * 获取首页个人日程数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180731
     */
    public function getHomeScheduleAction()
    {
        $loginUserId = Main::getLoginUserInfo('userId');
        $condition = "s.bDelete = 0 AND s.iUserId = $loginUserId";
        $result = $this->modelsManager->createBuilder()
            ->columns("s.iScheduleId,s.sScheduleName,s.tFromAt,s.tEndAt,u.sStaffName,s.iScheduleStatus")
            ->addFrom('Admin\Models\pm\XhpmSchedule', 's')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 's.iUserId = u.iUserId', 'u')
            ->where($condition)
            ->orderBy('s.iScheduleId desc')
            ->getQuery()
            ->execute()
            ->toArray();
        $data = array();
        if ($result) {
            foreach ($result as $key => $value) {
                $end = $value['tEndAt'];
                $status = $value['iScheduleStatus'];
                if ($status == 1 && strtotime($end) >= time()) {//未开始 未过期
                    $color = '#CCCCCC';
                } elseif ($status == 2 && strtotime($end) >= time()) {//进行中 未过期
                    $color = '#6495ED';
                } elseif ($status == 3) {//已完成
                    $color = '#66CDAA';
                } elseif ($status == 4) {//已关闭
                    $color = '#EEEE00';
                } elseif (in_array($status, [1, 2]) && $end < time()) {//过期未完成
                    $color = '#EE3B3B';
                }
                $data[] = array(
                    'id' => $value['iScheduleId'],
                    'title' => $value['sStaffName'] . ' : ' . $value['sScheduleName'],
                    'start' => $value['tFromAt'],
                    'end' => $value['tEndAt'],
                    'color' => $color,
                    'eventColor' => $color,
                );
            }
        }
        return $this->sendJsonResponse($data);
    }


    /**
     * 日程页面
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180424
     */
    public function scheduleAction()
    {
        if (!Power::exist('Bpm_Schedule')) {
            return $this->sendViewError('无日程权限');
        }
        $username = Main::getLoginUserInfo('userName');
        Template::exists('Schedule_User', 'list')
        or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106008));
        $schSearchArr[] = array('type' => 'text', 'id' => 'userListSearch', 'label' => '搜索： ');
        $this->view->setVars([
            'username' => $username,
        ]);
        $this->view->pick('schedule/userSchedule');
        Assets::importJs('js/myMain.js');
        Assets::easyUI('js/schedule/userSchedule.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::FullCalendar();
        Main::showNavPosition();
    }

    /**
     * 日程数据获取
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180423
     */
    public function getListAction()
    {
        if (!Power::exist('Bpm_Schedule')) {
            return $this->sendErrorResponse(500, '权限不足', '无日程权限');
        }
        $loginUserId = Main::getLoginUserInfo('userId');
//        $scheduleType = $this->request->getPost('iScheduleType','int') ? $this->request->getPost('iScheduleType','int') : 2;//获取日程类型  没有的话默认为1
        $iUserId = $this->request->getPost('iUserId', 'int'); //获取要查寻的人的日程
        $ifSelf = $this->request->getPost('justself', 'int'); //只看自己
        $uname = $this->request->getPost('uname', 'string'); //根据uname搜索
        $uids = $this->getUserIds($uname); //获取能查看的人员列表
//        $condition  = "s.bDelete = 0 AND s.iScheduleType = $scheduleType";
        $condition = "s.bDelete = 0 ";
        if ($ifSelf) {
            $condition .= " AND s.iUserId = $loginUserId";
        } elseif ($iUserId && $uids && in_array($iUserId, $uids)) {
            $condition .= " AND s.iUserId = $iUserId";
        } else {
            if ($uids) {
                $condition .= " AND (s.iUserId = $loginUserId  or s.iUserId in({uids:array})) ";
            } else {
                $condition .= " AND s.iUserId = $loginUserId ";
            }
        }
        if ($uids) {
            $result = $this->modelsManager->createBuilder()
                ->columns("s.iScheduleId,s.sScheduleName,s.tFromAt,s.tEndAt,u.sStaffName,s.iScheduleStatus")
                ->addFrom('Admin\Models\pm\XhpmSchedule', 's')
                ->leftjoin('Admin\Models\hrm\XhhrmStaff', 's.iUserId = u.iUserId', 'u')
                ->where($condition, ["uids" => $uids])
                ->orderBy('s.iScheduleId desc')
                ->getQuery()
                ->execute()
                ->toArray();
        } else {
            $result = $this->modelsManager->createBuilder()
                ->columns("s.iScheduleId,s.sScheduleName,s.tFromAt,s.tEndAt,u.sStaffName,s.iScheduleStatus")
                ->addFrom('Admin\Models\pm\XhpmSchedule', 's')
                ->leftjoin('Admin\Models\hrm\XhhrmStaff', 's.iUserId = u.iUserId', 'u')
                ->where($condition)
                ->orderBy('s.iScheduleId desc')
                ->getQuery()
                ->execute()
                ->toArray();
        }
        $data = array();
        if ($result) {
            foreach ($result as $key => $value) {
                $end = $value['tEndAt'];
                $status = $value['iScheduleStatus'];
                if ($status == 1 && strtotime($end) >= time()) {//未开始 未过期
                    $color = '#CCCCCC';
                } elseif ($status == 2 && strtotime($end) >= time()) {//进行中 未过期
                    $color = '#6495ED';
                } elseif ($status == 3) {//已完成
                    $color = '#66CDAA';
                } elseif ($status == 4) {//已关闭
                    $color = '#EEEE00';
                } elseif (in_array($status, [1, 2]) && $end < time()) {//过期未完成
                    $color = '#EE3B3B';
                }
                $data[] = array(
                    'id' => $value['iScheduleId'],
                    'title' => $value['sStaffName'] . ' : ' . $value['sScheduleName'],
                    'start' => $value['tFromAt'],
                    'end' => $value['tEndAt'],
                    'color' => $color,
                    'eventColor' => $color,
                );
            }
        }
        return $this->sendJsonResponse($data);
    }

    /**
     * 创建或者编辑日程表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180423
     */
    public function addScheduleFormAction()
    {
        $iScheduleId = $this->request->getQuery('iScheduleId', 'int');
        $schedule = $iScheduleId ? $schedule = XhpmSchedule::findFirst(
            [
                'conditions' => "bDelete = 0 AND iScheduleId = $iScheduleId "
            ]
        ) : new XhpmSchedule();
        $iUserId = $this->request->getQuery('iUserId', 'int');
        Assets::datetimePicker();
        Assets::easyUI('js/schedule/addSchedule.js');
        Assets::importJs('js/myMain.js');
        Template::exists('Schedule_User', 'list')
        or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106008));
        $SearchArr[] = array('type' => 'text', 'id' => 'SchoolList_Search', 'label' => '搜索： ');
        $SearchToolbar = Template::createSearchToolBar($SearchArr);
        $this->view->setVars([
            'ScheduleUser' => Template::createList('ScheduleUser', 'Schedule_User', array(
                'searchToolbar' => $SearchToolbar,
                'checkbox' => false,
                'field' => array('iUserId', 'sStaffName', 'sPostName', 'depname'),
                'tableAttr' => array(
                    'singleSelect' => 'true'
                )
            )),
            'iUserId' => $iUserId,
            'schedule' => $schedule,
            'scheduleId' => $iScheduleId,
        ]);
        $this->view->pick('schedule/addSchedule');
    }

    /**
     * 自建/修改日程
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180423
     */
    public function addScheduleAction()
    {
        $scheduleId = $this->request->getPost('iScheduleId', 'int');
        $status = $this->request->getPost('iScheduleStatus', 'int');
        $iUserId = Main::getLoginUserInfo('userId');
        try {
            $this->db->begin();
            if ($scheduleId) {
                if (!Power::exist('Bpm_Schedule_Edit')) {
                    return $this->sendErrorResponse(500, '权限不足', '无编辑日程权限');
                };
                //编辑
                $scheduleObj = XhpmSchedule::findFirst([
                    'conditions' => "bDelete = 0 AND iScheduleId = $scheduleId"
                ]);
                if ($scheduleObj) {
                    if ($scheduleObj->iUserId != $iUserId && !User::isAdmin()) {
                        return $this->sendErrorResponse(500, '编辑日程失败', '非日程所有者');
                    }
                } else {
                    return $this->sendErrorResponse(500, '编辑日程失败', '日程不存在');
                }
                if (in_array($scheduleObj->iScheduleStatus, [3, 4])) {
                    return $this->sendErrorResponse(500, '编辑日程失败', '日程已完成或已关闭');
                }
            } else {
                if (!Power::exist('Bpm_Schedule_Add')) {
                    return $this->sendErrorResponse(500, '权限不足', '无新增日程权限');
                };
                //新增
                $scheduleObj = new XhpmSchedule();
                $scheduleObj->iUserId = $iUserId;
            }
            $scheduleObj->assign($this->request->getPost());
            $re = $scheduleObj->save();
            if (!$re) {
                $this->db->rollback();
                return $scheduleId ? $this->sendErrorResponse(500, '编辑日程失败') : $this->sendErrorResponse(500, '创建日程失败');
            }
            $taskId = $scheduleObj->iTaskId;
            if ($scheduleObj->iTaskId) {
                $taskObj = XhpmProjectTask::findFirst([
                    'conditions' => "bDelete = 0 AND iTaskId = $taskId ",
                    'for_update' => true,
                ]);
                if ($taskObj) {
                    $taskObj->iTaskStatus = $status;
                    $taskObj->sTaskName = $this->request->getPost('sScheduleName');
                    $taskObj->sTaskContent = $this->request->getPost('sScheduleContent');
                    $taskObj->tFromAt = $this->request->getPost('tFromAt');
                    $taskObj->tEndAt = $this->request->getPost('tEndAt');
                    if ($status == 2) {
                        $taskObj->tStartedAt = date('Y-m-d H:i:s', time());
                    }
                    if ($status == 3) {
                        $taskObj->tFinishedAt = date('Y-m-d H:i:s', time());
                        $taskObj->iProcess = 100;
                    }
                    $res = $taskObj->save();
                    if (!$res) {
                        $this->db->rollback();
                        return $this->sendErrorResponse(400, '编辑日程失败', '日程对应任务状态变更失败');
                    }
                    //完成和关闭加入项目统计表
                    if (in_array($status, [3, 4])) {
                        $project = XhpmProject::findFirst([
                            'columns' => 'iProjectGrade,iParentPid',
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $taskObj->iProjectId),
                        ]);
                        $fatherProject = XhpmProject::findFirst([
                            'columns' => 'iProjectId',
                            'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                            'bind' => array('iProjectId' => $project->iParentPid),
                        ]);
                        $grade = $project->iProjectGrade;
                        if ($grade == 1) {
                            $projectCount = XhpmProjectCount::findFirst(
                                [
                                    'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                                    'bind' => array('iProjectId' => $taskObj->iProjectId),
                                    'for_update' => true
                                ]
                            );
                            $status == 3 ? $projectCount->iFinishedTaskNum = $projectCount->iFinishedTaskNum + 1
                                :
                                $projectCount->iSumTaskNum = $projectCount->iSumTaskNum - 1;
                            $res = $projectCount->save();
                        } elseif ($grade == 2) {
                            if (!$fatherProject) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '操作失败', '参数错误');
                            }
                            $projectCount = XhpmProjectCount::findFirst(
                                [
                                    'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                                    'bind' => array('iProjectId' => $taskObj->iProjectId),
                                    'for_update' => true
                                ]
                            );
                            $status == 3 ? $projectCount->iFinishedTaskNum = $projectCount->iFinishedTaskNum + 1
                                : $projectCount->iSumTaskNum = $projectCount->iSumTaskNum - 1;
                            $res = $projectCount->save();
                        } elseif ($grade == 3) {
                            if (!$fatherProject) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(400, '操作失败', '参数错误');
                            }
                            $fprojectCount = XhpmProjectCount::findFirst(
                                [
                                    'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                                    'bind' => array('iProjectId' => $fatherProject->iProjectId),
                                    'for_update' => true
                                ]
                            );
                            $status == 3 ? $fprojectCount->iFinishedTaskNum = $fprojectCount->iFinishedTaskNum + 1
                                : $fprojectCount->iSumTaskNum = $fprojectCount->iSumTaskNum - 1;
                            $res1 = $fprojectCount->save();
                            if ($res1) {
                                $projectCount = XhpmProjectCount::findFirst(
                                    [
                                        'conditions' => 'bDelete=0 AND iProjectId=:iProjectId:',
                                        'bind' => array('iProjectId' => $taskObj->iProjectId),
                                        'for_update' => true
                                    ]
                                );
                                $status == 3 ? $projectCount->iFinishedTaskNum = $projectCount->iFinishedTaskNum + 1
                                    : $projectCount->iSumTaskNum = $projectCount->iSumTaskNum - 1;
                                $res = $projectCount->save();
                            }
                        }
                        if (!$res) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '操作失败', '参数错误');
                        }
                    }
                }
            }

            $this->db->commit();
            return json_encode(['id' => $scheduleObj->iScheduleId, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 获取日程用户
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180423
     */
    public function getScheduleUserAction()
    {
        $conditions = 's.bDelete = 0 and u.bDelete = 0 AND s.iStaffStatus = 1 ';
        $deps = User::getextrapower('dep', 'schedule');//返回一个数组[5,6,7,depid]
        if (!$deps) {
            return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
        }
        $uname = $this->request->getPost('uname', 'string');
        if ($uname) {
            $conditions .= " AND (s.sStaffName like '%" . $uname . "%' ) ";
        } else {
            $deps = implode(",%' OR  sDepIds like '%,", $deps);
            $conditions .= " AND (s.sDepIds like '%," . $deps . ",%' ) ";
        }
        $builder = $this->modelsManager->createBuilder()
            ->columns("s.iUserId,s.sStaffName,s.sPostName,s.sDepIds")
            ->addFrom('Admin\Models\hrm\XhhrmStaff', 's')
            ->join('Admin\Models\user\XhsysUser', 's.iUserId = u.iUserId', 'u')
            ->where($conditions);
        $staffs = Main::runBuilderPaginator($builder, true);
        foreach ($staffs['rows'] as $k => $staff) {
            $dep = $staff['sDepIds'];
            if ($dep) {
                $dep = explode(',', $dep);
            }
            $depId = $dep[1];
            if ($depId) {
                $depname = XhhrmDepart::findFirst(
                    ['columns' => "sDepName",
                        'conditions' => "iDepId = $depId"
                    ]
                );
            }

            $staffs['rows'][$k]['sDepName'] = $depname ? $depname->sDepName : '';
        }
        return $this->sendJsonResponse($staffs);
    }

    /**
     * 获取能查看的员工列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180520
     */
    private function getUserIds($uname)
    {
        $deps = User::getextrapower('dep', 'schedule');//取扩展部门权限
        if (!$deps) {
            return [];
        }
        $deps = implode(",%' OR  sDepIds like '%,", $deps);
        $conditions = 'bDelete = 0 AND iStaffStatus = 1';
        if ($uname) {
            $conditions .= " AND sStaffName like '%" . $uname . "%'";
        }
        $conditions .= " AND (sDepIds like '%," . $deps . ",%' ) ";
        $users = $this->modelsManager->createBuilder()
            ->columns("iUserId")
            ->From('Admin\Models\hrm\XhhrmStaff')
            ->where($conditions)
            ->getQuery()
            ->execute()
            ->toArray();
        $uids = [];
        foreach ($users as $k => $user) {
            $uids[] = $user['iUserId'];
        }
        return $uids;
    }

    /**
     * 删除日程
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180820
     */
    public function delScheduleByIdAction()
    {
        $scheduleId = $this->request->getPost('iScheduleId', 'int');
        $iUserId = Main::getLoginUserInfo('userId');
        try {
            $this->db->begin();
            if ($scheduleId) {
                if (!Power::exist('Bpm_Schedule_Del')) {
                    return $this->sendErrorResponse(500, '权限不足', '无删除日程权限');
                };
                //编辑
                $scheduleObj = XhpmSchedule::findFirst([
                    'conditions' => "bDelete = 0 AND iScheduleId = $scheduleId"
                ]);
                if ($scheduleObj) {
                    if ($scheduleObj->iUserId != $iUserId && !User::isAdmin()) {
                        return $this->sendErrorResponse(500, '操作失败', '非日程所有者');
                    }
                } else {
                    return $this->sendErrorResponse(500, '操作失败', '日程不存在');
                }
            } else {
                return $this->sendErrorResponse(500, '操作失败', '日程不存在');
            }
            $scheduleObj->bDelete = 1;
            $re = $scheduleObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败');
            }

            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 获取日程用户
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180802
     */
    public function getScheduleUserNumAction()
    {
        $conditions = 's.bDelete = 0 and u.bDelete = 0 AND s.iStaffStatus = 1 ';
        $deps = User::getextrapower('dep', 'schedule');//返回一个数组[5,6,7,depid]
        if (!$deps) {
            return $this->sendJsonResponse(['num' => 0]);
        }
        $deps = implode(",%' OR  sDepIds like '%,", $deps);
        $conditions .= " AND (s.sDepIds like '%," . $deps . ",%' ) ";
        $staffs = $this->modelsManager->createBuilder()
            ->columns("s.iUserId,s.sStaffName,s.sPostName,s.sDepIds")
            ->addFrom('Admin\Models\hrm\XhhrmStaff', 's')
            ->join('Admin\Models\user\XhsysUser', 's.iUserId = u.iUserId', 'u')
            ->where($conditions)
            ->getQuery()
            ->execute()
            ->toArray();

        return $this->sendJsonResponse(['num' => count($staffs)]);
    }

}

